<template>
  <div class="container mx-auto px-4 py-8">
    <h2 class="text-2xl font-bold mb-6">房屋管理</h2>
    <div class="flex justify-between items-center mb-4">
      <button @click="openCreateModal" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition-all duration-300 transform hover:scale-105">
        <i class="fa fa-plus mr-2"></i>新增房屋
      </button>
      <div class="relative">
        <input 
          v-model="searchQuery" 
          @input="debouncedSearch" 
          type="text" 
          placeholder="搜索房屋..." 
          class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        >
        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
      </div>
    </div>
    
    <div class="overflow-x-auto">
      <table class="min-w-full bg-white rounded-lg shadow-md overflow-hidden">
        <thead>
          <tr class="bg-gray-50">
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">楼号</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">单元</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">房号</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">面积</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">业主</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入住时间</th>
            <th class="py-3 px-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200">
          <tr v-for="house in filteredHouses" :key="house.id" class="hover:bg-gray-50 transition-colors duration-200">
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ house.id }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ house.buildingNumber }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ house.unitNumber }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ house.roomNumber }}</td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">{{ house.area }}m²</td>
            <td class="py-4 px-4 whitespace-nowrap">
              <span :class="{
                'px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800': house.owners && house.owners.length > 0,
                'px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800': !house.owners || house.owners.length === 0
              }">
                {{ house.owners && house.owners.length > 0 ? '已入住' : '空置' }}
              </span>
            </td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">
              {{ house.owners && house.owners.length > 0 ? house.owners[0].name : '-' }}
            </td>
            <td class="py-4 px-4 whitespace-nowrap text-sm text-gray-900">
              {{ house.checkInTime ? formatDate(house.checkInTime) : '-' }}
            </td>
            <td class="py-4 px-4 whitespace-nowrap text-sm font-medium">
              <button @click="openEditModal(house)" class="text-indigo-600 hover:text-indigo-900 mr-3 transition-colors duration-200">
                <i class="fa fa-edit mr-1"></i>编辑
              </button>
              <button @click="deleteHouse(house.id)" class="text-red-600 hover:text-red-900 transition-colors duration-200">
                <i class="fa fa-trash mr-1"></i>删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 分页组件 -->
    <div class="flex justify-between items-center mt-6">
      <div class="text-sm text-gray-700">
        显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, total) }} 条，共 {{ total }} 条
      </div>
      <div class="flex space-x-1">
        <button 
          :disabled="currentPage === 1" 
          @click="currentPage--" 
          class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-200"
        >
          <i class="fa fa-chevron-left"></i>
        </button>
        <button 
          v-for="page in pageCount" 
          :key="page" 
          :class="{
            'px-3 py-1 border border-blue-500 bg-blue-500 text-white rounded-md': page === currentPage,
            'px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50': page !== currentPage
          }" 
          @click="currentPage = page"
          class="transition-colors duration-200"
        >
          {{ page }}
        </button>
        <button 
          :disabled="currentPage === pageCount" 
          @click="currentPage++" 
          class="px-3 py-1 border border-gray-300 rounded-md bg-white text-gray-700 hover:bg-gray-50 transition-colors duration-200"
        >
          <i class="fa fa-chevron-right"></i>
        </button>
      </div>
    </div>
    
    <!-- 创建/编辑模态框 -->
    <div v-if="isModalOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 transform transition-all duration-300 scale-100 opacity-100">
        <div class="flex justify-between items-center p-6 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">
            {{ isEditing ? '编辑房屋信息' : '新增房屋' }}
          </h3>
          <button @click="closeModal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="p-6">
          <form @submit.prevent="submitForm">
            <div class="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label for="buildingNumber" class="block text-sm font-medium text-gray-700 mb-1">楼号</label>
                <input 
                  type="number" 
                  id="buildingNumber" 
                  v-model.number="formData.buildingNumber" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  required
                >
              </div>
              <div>
                <label for="unitNumber" class="block text-sm font-medium text-gray-700 mb-1">单元</label>
                <input 
                  type="number" 
                  id="unitNumber" 
                  v-model.number="formData.unitNumber" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  required
                >
              </div>
            </div>
            <div class="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label for="roomNumber" class="block text-sm font-medium text-gray-700 mb-1">房号</label>
                <input 
                  type="text" 
                  id="roomNumber" 
                  v-model="formData.roomNumber" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  required
                >
              </div>
              <div>
                <label for="area" class="block text-sm font-medium text-gray-700 mb-1">面积(m²)</label>
                <input 
                  type="number" 
                  id="area" 
                  v-model.number="formData.area" 
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  required
                >
              </div>
            </div>
            <div class="flex justify-end space-x-3 mt-6">
              <button type="button" @click="closeModal" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
                取消
              </button>
              <button type="submit" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
                {{ isEditing ? '保存修改' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 提示框 -->
    <div v-if="showToast" class="fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-md shadow-lg transform transition-all duration-500 translate-y-0 opacity-100 flex items-center z-50">
      <i class="fa fa-check-circle mr-2"></i>
      <span>{{ toastMessage }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      houses: [],
      filteredHouses: [],
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      isModalOpen: false,
      isEditing: false,
      formData: {
        id: null,
        buildingNumber: null,
        unitNumber: null,
        roomNumber: '',
        area: null
      },
      showToast: false,
      toastMessage: ''
    };
  },
  computed: {
    total() {
      return this.filteredHouses.length;
    },
    pageCount() {
      return Math.ceil(this.total / this.pageSize);
    },
    paginatedHouses() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredHouses.slice(start, end);
    }
  },
  created() {
    this.fetchHouses();
    // 创建防抖函数
    this.debouncedSearch = this.debounce(this.searchHouses, 300);
  },
  methods: {
    // 获取房屋列表
    async fetchHouses() {
      try {
        const response = await this.$axios.get('/api/houses');
        this.houses = response.data;
        this.filteredHouses = [...this.houses];
      } catch (error) {
        console.error('获取房屋列表失败:', error);
        this.showToastMessage('获取房屋列表失败', 'error');
      }
    },
    
    // 搜索房屋
    searchHouses() {
      if (!this.searchQuery.trim()) {
        this.filteredHouses = [...this.houses];
        return;
      }
      
      const query = this.searchQuery.toLowerCase().trim();
      this.filteredHouses = this.houses.filter(house => {
        return house.buildingNumber.toString().includes(query) ||
               house.unitNumber.toString().includes(query) ||
               house.roomNumber.toLowerCase().includes(query) ||
               (house.owners && house.owners.length > 0 && house.owners[0].name.toLowerCase().includes(query));
      });
      
      // 重置页码
      this.currentPage = 1;
    },
    
    // 打开创建模态框
    openCreateModal() {
      this.isEditing = false;
      this.formData = {
        buildingNumber: null,
        unitNumber: null,
        roomNumber: '',
        area: null
      };
      this.isModalOpen = true;
    },
    
    // 打开编辑模态框
    openEditModal(house) {
      this.isEditing = true;
      this.formData = {
        id: house.id,
        buildingNumber: house.buildingNumber,
        unitNumber: house.unitNumber,
        roomNumber: house.roomNumber,
        area: house.area
      };
      this.isModalOpen = true;
    },
    
    // 关闭模态框
    closeModal() {
      this.isModalOpen = false;
    },
    
    // 提交表单
    async submitForm() {
      try {
        if (this.isEditing) {
          // 更新房屋
          await this.$axios.put(`/api/houses/${this.formData.id}`, this.formData);
          this.showToastMessage('房屋信息更新成功');
        } else {
          // 创建房屋
          await this.$axios.post('/api/houses', this.formData);
          this.showToastMessage('房屋创建成功');
        }
        
        this.closeModal();
        this.fetchHouses();
      } catch (error) {
        console.error('提交表单失败:', error);
        this.showToastMessage('操作失败，请重试', 'error');
      }
    },
    
    // 删除房屋
    async deleteHouse(id) {
      if (confirm('确定要删除该房屋吗？')) {
        try {
          await this.$axios.delete(`/api/houses/${id}`);
          this.showToastMessage('房屋删除成功');
          this.fetchHouses();
        } catch (error) {
          console.error('删除房屋失败:', error);
          this.showToastMessage('删除失败，请重试', 'error');
        }
      }
    },
    
    // 显示提示消息
    showToastMessage(message, type = 'success') {
      this.toastMessage = message;
      this.showToast = true;
      
      // 设置提示框背景色
      const toastElement = document.querySelector('.fixed.bottom-4.right-4');
      if (toastElement) {
        if (type === 'error') {
          toastElement.classList.remove('bg-green-500');
          toastElement.classList.add('bg-red-500');
        } else if (type === 'warning') {
          toastElement.classList.remove('bg-green-500');
          toastElement.classList.add('bg-yellow-500');
        }
      }
      
      // 3秒后隐藏提示框
      setTimeout(() => {
        this.showToast = false;
      }, 3000);
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    
    // 防抖函数
    debounce(func, delay) {
      let timer = null;
      return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(context, args);
        }, delay);
      };
    }
  }
};
</script>

<style scoped>
/* 模态框动画 */
.fixed.inset-0.bg-black.bg-opacity-50 {
  transition: opacity 0.3s ease-in-out;
}

.fixed.inset-0.bg-black.bg-opacity-50 > div {
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

/* 表格行悬停效果 */
tbody tr {
  transition: background-color 0.2s ease-in-out;
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease-in-out;
}
</style>  